/****  Live Monitoring ****/
var map = null;
var geocoder = null;
var gpsList = [];
var markers = [];
var labels = [];
var infoWindow = null;
//Timer handler refresh data GPS
var timerGps = null;
//Timer interval refresh data GPS
var refreshInterval = 15000;
var tabOnline = null;


//panel collapse/expand

var selectedPoi = null;
var infoWindowPoi = null;
var infoWindowDistance = null;

var poi = null;
var fullscreen = false;
var trip_icon = "mobil";
//selected user id
var user_id = 0;
var bound = false;
var groupTree = [];
//Node Group Selected
var nodeGroup = null;


var paths = [];
var selectedMarker = null;
var selectedMarkerId = null;
var polygonEdit = null;

//var g = google.maps;
var marker = null;
var label = null;
var vh_id = null;
var polygons = [];
var requestHandler = null;
var requestHandlerTail = null;

var tail;
var tail_vh_id;
var tail_icon_visible = false;

var text_icon_visible = true;
var direction_icon_visible = true;

var center_gps_active = false;
var center_gps_vh_id = 0;
var center_gps_marker = null;
var gaugeShow = false;
var POIControlCreated = false;

var editTreeGPS = false;
/*
 * Grid Report
 * @type type
 */

var gridFuelReport = null;
var gridHourReport = null;

var nodeTree = null;
var toggleBtn = false;
var buttoncommands = [];
var reportPanel;

var btnDownload = null;

var reportSummary;
var measureTool = false;
var clickCount = 0;
var polyline = null;

var polygon = null;
var geofenceEdit = {
    edit_mode: false,
    id: 0,
    vh_id: 0,
    name: "",
    description: "",
    node: null, //selected nde
    polygon: null
};
var polygon_id = 0;
var clickMapHandler = null;
var maps = [];
var calculateDistance = false;
var calculateArea = false;
var bgColor = '';
var gaugeSpeed = null;
var gaugeFuel = null;
var gaugeSignalGsm = null;
var gaugeSignalGps = null;

//---------------- Trip Report Playback--------------------
var vh_trip_id = 0;
var trip_from = "";
var trip_to = "";
var trips = [];
var tripIndex = 0;
var pageNumber = 1;
var tripSpeed = 1000; //1/second
var tripHandler = null;
var infoWindowTrip = null;
var tripMarker = null;
var beginTripMarker = null;
var endTripMarker = null;
var tripEventMarker = [];
var tripPolyline = null;
var gridTripReport = null; //table_trip_report.php
var tripReportLayout = null;
var pagerGridTripReport = null;
var tripReqHandler = null;
var panelTripStatistic = null;
var avgTripSpeed = 0;
var tripDistance = 0;//google.maps.geometry.spherical.computeLength(tripPolyline.getPath().getArray()) / 1000;

var btnPlay = null;
var btnPause = null;
var btnStop = null;
var pause = false;


//---------------- End Playback Variable----------------
var sendCommands = [];
//Array Menyimpada Data Object GPS


var tiles = [];

/****** Main Layout index.php **********/
var layout = null;
var leftLayout = null;
var centerLayout = null;
var rightLayout = null;
var bottomLayout = null;

/***** Layout map_form.php *****/
var layout2 = null;
var centerLayout2 = null;
var bottomLayout2 = null;

/**** Left Layout ****/
/**** Treeview GPS ****/
var cboUserId;
var cboGpsId;

var treeGps;
var treeGpsOnline;
var treeGpsOffline;
var treePoi;



var cboFindGpsId;
var cboPlaybackId;

var treeGeofence;

var icons = [];

var dataGridUser;
var dialogUserForm;
var mainTabs = null;
var reportTabs = null;

/***** Form & Dialog ******/
var formUser = null;
var dlgUser = null;
var gridUser = null;
var formGps = null;
var dlgGps = null;
var gridGps = null;

var formPoi = null;
var dlgPoi = null;
var gridPoi = null;

var formProfile = null;
var dlgProfile = null;

var panelInfoGps = null;
var formGeofence = null;
var dlgGeofence = null;

var audioElement = null;
var maxLoop = 5;
var currentLoop = 0;
var initSound = true;

var btnCenter = false;

/*************************/
var label1 = null, label2 = null, label3 = null, label4 = null;
var optsKnob5 = ["WSAS", "ESB", "G-REG", "GS", "BAM"];
var timer;
var r;
var poi_image_save = "";
var gps_image_save = "";

var adminUserMode = '';
/*************************/

var lokalOpt = {
    getTileUrl: function(coord, zoom) {
        return "http://tiles.navigasi.net/navnet-hybrid/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    maxZoom: 18,
    minZoom: 0,
    name: "Lokal"
};
var lokalType = new google.maps.ImageMapType(lokalOpt);
init_map = function() {
    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(-0.789275, 113.921327),
        panControl: true,
        zoomControl: true,
        scaleControl: true,
        streetViewControl: false,
        overviewMapControl: false,
        //disableDefaultUI: true

        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, 'Lokal']
        }
    };
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    map.mapTypes.set('Lokal', lokalType);
    //console.log('init_map');
//    google.maps.event.trigger(map, 'resize', function() {
//        tripReportLayout.layout('resize');
//    });

    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
        // console.log('show_speedometer();');
        //mainTabs.tabs("resize");
        show_speedometer();
        //show_logo();
        //show_trip_control();
        update_speedometer(0, 0, 0, 0);//Speed, GSM, GPS       
    });
};


/****************/
function onKnobChange1(val) {
    label1.update(val != 0 ? Math.round(val) : "0");
}
function onKnobChange2(val) {
    label2.update(val != 0 ? Math.round(val) : "0");
}
function onKnobChange3(val) {
    label3.update(val != 0 ? Math.round(val) : "0");
}
function onKnobChange4(val) {
    label4.update(val != 0 ? Math.round(val) : "0");
}
function onKnobChange5(val) {
    label5.update(optsKnob5[Math.round(val)]);
}

function drawKnobs(r, offsetX, offsetY) {
    var k1, k2, k3, k4;
    new wso2vis.ctrls.Label().text("KNOBS").fontsize(20).create(r, offsetX + 280, offsetY + 20);

    k1 = new wso2vis.ctrls.Knob().dialRadius(40).smallTick(10).largeTick(10).minVal(0).maxVal(100)
            .snap(true).create(r, offsetX + 80, offsetY + 120);
    k1.onChange = onKnobChange1;
    label1 = new wso2vis.ctrls.Label().text("0").create(r, offsetX + 80, offsetY + 200);

    k2 = new wso2vis.ctrls.Knob().dialRadius(40).smallTick(4).largeTick(20).minVal(-100).maxVal(100)
            .startVal(0).snap(false).create(r, offsetX + 260, offsetY + 120);
    k2.onChange = onKnobChange2;
    label2 = new wso2vis.ctrls.Label().text("0").create(r, offsetX + 260, offsetY + 200);

    k3 = new wso2vis.ctrls.Knob().dialRadius(30).smallTick(1).largeTick(1)
            .minVal(0).maxVal(4).minAngle(135).maxAngle(225)
            .snap(true).create(r, offsetX + 80, offsetY + 320);
    k3.onChange = onKnobChange3;
    label3 = new wso2vis.ctrls.Label().text("0").create(r, offsetX + 80, offsetY + 360);

    k4 = new wso2vis.ctrls.Knob().dialRadius(30).smallTick(5).largeTick(10)
            .minVal(30).maxVal(80).minAngle(135).maxAngle(225)
            .snap(false).create(r, offsetX + 260, offsetY + 320);
    k4.onChange = onKnobChange4;
    label4 = new wso2vis.ctrls.Label().text("30").create(r, offsetX + 260, offsetY + 360);

    k5 = new wso2vis.ctrls.Knob().dialRadius(40).minAngle(210).maxAngle(330)
            .selectOpts(optsKnob5).create(r, offsetX + 500, offsetY + 220);
    k5.onChange = onKnobChange5;
    label5 = new wso2vis.ctrls.Label().text("WSAS").create(r, offsetX + 500, offsetY + 300);
}

function drawCircularGauges(r, offsetX, offsetY) {
    var g1, g2, g3, g5;

    function globalTick()
    {
        var minVal = 0, maxVal = 100;
        var val = Math.floor(minVal + Math.random() * (maxVal - minVal))
        //g1.setValue(val);
        g2.setValue(val);
        g3.setValue(val / 25);
        g4.setValue(50 - val);
        g5.setValue(val / 25);
    }
    ;

    //new wso2vis.ctrls.Label() .text("CIRCULAR GAUGES") .fontsize(20) .create(r, offsetX + 370, offsetY + 20); 

//    g1 = new wso2vis.ctrls.CGauge().dialRadius(40).smallTick(1).largeTick(10).minVal(0).maxVal(100)
//            .ltlen(18).stlen(15).needleCenterRadius(10).needleBottom(20)
//            .labelOffset(15).labelFontSize(15)
//            .create(r, offsetX + 60, offsetY + 20);
//            .create(r, offsetX + 160, offsetY + 200);

    g2 = new wso2vis.ctrls.CGauge().dialRadius(40).smallTick(4).largeTick(20).minVal(0).maxVal(150)
            .minAngle(0).maxAngle(270)
            .create(r, offsetX + 60, offsetY + 100);

    g4 = new wso2vis.ctrls.CGauge().dialRadius(60).smallTick(5).largeTick(10)
            .minVal(-50).maxVal(50).minAngle(100).maxAngle(260)
            .create(r, offsetX + 60, offsetY + 500);

    g3 = new wso2vis.ctrls.CGauge().dialRadius(30).smallTick(0.5).largeTick(1)
            .minVal(0).maxVal(4).minAngle(135).maxAngle(225)
            .needleLength(28).needleCenterRadius(1).needleBottom(8).ltlen(4).stlen(4)
            .create(r, offsetX + 60, offsetY + 250);

    g5 = new wso2vis.ctrls.CGauge().dialRadius(30).smallTick(0.5).largeTick(1)
            .minVal(0).maxVal(4).minAngle(225).maxAngle(315)
            .needleLength(28).needleCenterRadius(1).needleBottom(8).ltlen(4).stlen(4)
            .create(r, offsetX + 60, offsetY + 400);

    globalTick();

    timer = setInterval(globalTick, 2000);
}

function clearAll() {
    r.clear();
    clearInterval(timer);
}
/******************************/

full_screen = function() {
    if (fullscreen === true) {
        layout.layout('expand', 'west');
        layout.layout('expand', 'north');
        layout.layout('expand', 'south');
        fullscreen = false;
        return;
    }
    layout.layout('collapse', 'west');
    layout.layout('collapse', 'north');
    layout.layout('collapse', 'south');
    fullscreen = true;
};
send_command = function(cmd) {

////DATA_TYPE|ID_CLIENT|GPS_BRAND|IMEI|CMD_TYPE
    //console.log("Parse Node Tree Object");
    //console.log(nodeTree);

    //   console.log("ToggleButton:" + toggleBtn);
    //  var btn = $("#btn_engineoff");
    //  console.log(btn);
    //change button
    // toggleBtn = !toggleBtn;
    //  buttoncommands[cmd] = !buttoncommands[cmd];


    var command;
    if (nodeTree === null) {
        return;
    }
    var gps = nodeTree.gps_brand;
    if (gps === "GT06" || gps === "GT07" || gps === "GT06N" || gps === "GT02" || gps === "GT03A" || gps === "GT07" || gps === "TR02" || gps === "TR06") {
        console.log("Command Geothinking Product");
        switch (cmd) {
            case "restart":
                command = "RESET#";
                break;
            case "engineoff":
                command = "RELAY,1#";
                break;
            case "engineon":
                command = "RELAY,0#";
                break;
            case "position":
                command = "WHERE#";
                break;
        }
    } else if (gps === "GTLT") {
        // console.log("Command GTLT");
    } else {
        //console.log("Command UNKNOW GPS");
    }
    var id_client = Math.floor((Math.random() * 1000) + 1);
    var params = "SEND_COMMAND|" + id_client + "|" + nodeTree.gps_brand + "|" + nodeTree.imei + "|" + command;
    //console.log("Params:" + params);
    reqCommandHandler = $.ajax({
        crossDomain: true,
        url: "http://107.170.13.48:8844", //url: "http://192.168.1.4:8844"
        data: {
            cmd: params
        }
    }
    );
    reqCommandHandler.done(function(msg) {
        alert(msg);
    });

    reqCommandHandler.fail(function(jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
};

center_gps = function() {
    if (center_gps_active === true) {
        center_gps_vh_id = 0;
        center_gps_active = false;
        center_gps_marker = null;
        return;
    }
    center_gps_marker = selectedMarker;
    center_gps_vh_id = selectedMarkerId;
    center_gps_active = true;

    if (center_gps_marker !== null) {
        map.setCenter(center_gps_marker.getPosition());
    }
};

/*
 * change_icon_mode
 * Param 1: icon_only,icon_tile, icon_angle
 * @returns {undefined}
 */
show_text_icon = function() {
    if (text_icon_visible === true) {
        text_icon_visible = false;
        if (labels) {
            for (i in labels) {
                labels[i].setMap(null);
            }
        }
    } else {
        text_icon_visible = true;
        if (labels) {
            for (i in labels) {
                labels[i].setMap(map);
            }
        }
    }
};

show_trip_control = function() {
    var tripControlDiv = document.createElement('div');
    //logoControlDiv.className = 'gauge';
    var tripControl = new TripControl(tripControlDiv);
    tripControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(tripControlDiv);
};

show_logo = function() {
    var logoControlDiv = document.createElement('div');
    //logoControlDiv.className = 'gauge';
    var logoControl = new LogoControl(logoControlDiv);
    logoControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
};

show_map_control = function() {
    if (gaugeShow === true) {
        return;
    }
    var mapControlDiv = document.createElement('div');
    mapControlDiv.className = 'gauge';
    var mapControl = new MapControl(mapControlDiv);
    mapControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(mapControlDiv);

};
show_speedometer = function() {
    if (gaugeShow === true) {
        return;
    }
    var homeControlDiv = document.createElement('div');
    homeControlDiv.className = 'gauge';
    var homeControl = new HomeControl(homeControlDiv);
    homeControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(homeControlDiv);

    gaugeSpeed = jQuery("#gauge_speed").gauge({
        min: 0,
        max: 200,
        label: 'Speed/Km',
        bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSpeed.gauge('setValue', 0);

    gaugeFuel = jQuery("#gauge_fuel").gauge({
        min: 0,
        max: 100,
        label: 'BBM'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeFuel.gauge('setValue', 40);

    gaugeSignalGsm = jQuery("#gauge_signal_gsm").gauge({
        min: 0,
        max: 10,
        label: 'Signal GSM'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSignalGsm.gauge('setValue', 6);

    gaugeSignalGps = jQuery("#gauge_signal_gps").gauge({
        min: 0,
        max: 30,
        label: 'Satelite'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSignalGps.gauge('setValue', 16);

    gaugeShow = true;
};
/**
 * The HomeControl adds a control to the map that simply
 * returns the user to Chicago. This constructor takes
 * the control DIV as an argument.
 * @constructor
 */
function MapControl(controlDiv) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = 'transparent';
    controlUI.style.borderStyle = 'dash';
    controlUI.style.width = '150px';
    controlUI.style.height = '400px';
    controlUI.style.borderWidth = '1px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.style.display = "block";
    //controlUI.title = 'Click to set the map to Home';
    controlUI.id = 'gauge_container';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('div');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    //controlText.style.paddingLeft = '4px';
    //controlText.style.paddingRight = '4px';
    controlText.innerHTML =
            "<a id='btn_zoomin' href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-zoomin' plain='false' onclick='map.setZoom(map.getZoom() + 1);'>Zoom In</a>";
    controlUI.appendChild(controlText);
}
function HomeControl(controlDiv) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = 'transparent';
    controlUI.style.borderStyle = 'dash';
    controlUI.style.width = '150px';
    controlUI.style.height = '400px';
    controlUI.style.borderWidth = '1px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.style.display = "block";
    //controlUI.title = 'Click to set the map to Home';
    controlUI.id = 'gauge_container';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('div');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    //controlText.style.paddingLeft = '4px';
    //controlText.style.paddingRight = '4px';
    controlText.innerHTML = "<canvas id='gauge_speed' width='120' height='110'></canvas>" +
            "<canvas id='gauge_fuel' width='120' height='110'></canvas>" +
            "<canvas id='gauge_signal_gsm' width='120' height='110'></canvas>" +
            "<canvas id='gauge_signal_gps' width='120' height='110'></canvas>";
    controlUI.appendChild(controlText);
}

/*
 * Cek inf point inside polygon 
 * @param {type} mode
 * @returns {undefined}
 * var geofenceObject={
 *  
 * }
 */
//Berfungsi menyimpan semua polygon client
//index menunjukkan id gps, didalam index terdapat object
//1. polygons
//2. subgeofence 
//GPSGeofence, GPS that have geofence active
var GPSGeofenceList = [];
var GeofenceList = {
    imei: '',
    list: []
};
var Geofence = {
    prevLatLng: null,
    currentLatLng: null,
    prevInside: false,
    currInside: false,
    enter_alarm: false,
    exit_alarm: false,
    polygon: null
};
point_inside_polygon = function(id, latlng) {
    var GFList = GPSGeofenceList[id];

    for (var i = 0; i < GFList.list.length; i++) {
        var GF = GFList.list[i];
        if (google.maps.geometry.poly.containsLocation(latlng, GF.polygon)) {
            if (GF.prevInside === false && GF.enter_alarm === true) {
                play_sound();
            }
        } else {
            if (GF.prevInside === true && GF.exit_alarm === true) {
                play_sound();
            }
        }
    }
};
function GeofenceVehicle(_nopol, _imei)
{
    this.nopol = _nopol;
    this.imei = _imei;
    this.list = [];
}

function Geofence(enter_alarm, exit_alarm, polygon)
{
    this.enter_alarm = enter_alarm;
    this.exit_alarm = exit_alarm;
    this.polygon = polygon;
}

/*
 * Measure Area
 * @param {type} state
 * @returns {undefined}
 */
change_map_mode = function(mode) {
    switch (mode) {
        case 'addpoi':
            break;
        case 'addgeofence':
            break;
        case 'playback':
            stop_timer();
            if (markers) {
                for (i in markers) {
                    markers[i].setMap(null);
                }
            }
            if (labels) {
                for (i in labels) {
                    labels[i].setMap(null);
                }
            }
            if (polyline) {
                polyline.setMap(null);
            }

            break;
        case 'live':
            if (markers) {
                for (i in markers) {
                    markers[i].setMap(map);
                }
            }
            if (labels) {
                for (i in labels) {
                    labels[i].setMap(map);
                }
            }
            if (polyline) {
                polyline.setMap(map);
            }
            clear_trip();
            refresh_gps();
            break;
    }
};
reset_bg_toolbar_button = function() {
    $("#btn_measure_area").css("background-color", '#08088A');
    $("#btn_measure_line").css("background-color", '#08088A');
};
enable_measure_area_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateArea === true) {
        calculateArea = false;
        close_measure_tool();
        return;
    }
    //Clear existing previous tool
    polygon = new google.maps.Polygon({
        map: map,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        draggable: true,
        editable: true,
        geodesic: true
    });
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation2);
    $("#btn_measure_area").css("background-color", '#ff0000');
    calculateArea = true;
};
update_area = function() {
    var path = polygon.getPath();
    var distance = google.maps.geometry.spherical.computeArea(path.getArray()) / 1000;
    if (infoWindowDistance !== null)
        infoWindowDistance.close();
    infoWindowDistance = new google.maps.InfoWindow({content: "Luas " + distance.toFixed(2) + " Km2"});
    infoWindowDistance.open(map);
    infoWindowDistance.setPosition(event.latLng);
};
/*
 * Measure Distance
 * @param {type} event
 * @returns {undefined}
 */
enable_measure_line_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateDistance === true) {
        calculateDistance = false;
        return;
    }
    //Clear existing previous tool
    close_measure_tool();
    var polyOptions = {
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };
    polyline = new google.maps.Polyline(polyOptions);
    polyline.setMap(map);
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation);
    $("#btn_measure_line").css("background-color", '#FF0000');
    calculateDistance = true;
};
close_measure_tool = function() {
    if (polyline !== null) {
        clearPaths();
        polyline.setMap(null);
    }
    if (polygon !== null) {
        polygon.setMap(null);
    }
    if (clickMapHandler !== null) {
        google.maps.event.removeListener(clickMapHandler);
    }
    //$("#text_measure").hide();
};
function addLocation(event) {
    var path = polyline.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeLength(path.getArray()) / 1000;
    // document.getElementById('text_measure').value = "Jarak " + distance.toFixed(2) + " Km";

    if (infoWindowDistance !== null)
        infoWindowDistance.close();
    infoWindowDistance = new google.maps.InfoWindow({content: "Jarak " + distance.toFixed(2) + " Km"});
    infoWindowDistance.open(map);
    infoWindowDistance.setPosition(event.latLng);
}
function addLocation2(event) {
    var path = polygon.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeArea(path.getArray()) / 1000;
    if (infoWindowDistance !== null)
        infoWindowDistance.close();
    infoWindowDistance = new google.maps.InfoWindow({content: "Luas " + distance.toFixed(2) + " Km2"});
    infoWindowDistance.open(map);
    infoWindowDistance.setPosition(event.latLng);
}

function clearPaths() {
    var path = polyline.getPath();
    while (path.getLength()) {
        path.pop();
    }
}

init_tail = function() {
    var polyOptions = {
        strokeColor: '#0000A0',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };
    tail = new google.maps.Polyline(polyOptions);
    tail.setMap(map);
};
clear_tail = function() {
    if (tail == null)
        return;
    tail_vh_id = 0;
    tail.setMap(null);
    tail = null;
};
set_timer = function(timer) {
    refreshInterval = timer.value;
    load_vehicle_data();
};
stop_timer = function() {
    if (requestHandler)
        requestHandler.abort();
    clearTimeout(timerGps);
};
get_speed_state = function(speed) {
    if (speed >= 3) {
        return "Bergerak";
    } else {
        return "Berhenti";
    }
};

create_iw_content = function(data) {
    var str_alarm = "";
    if (data.alarm_id >= 1) {
        str_alarm = "<tr><td style='width:90px;'>Imei</td><td>:</td><td>" + get_alarm_name(data.alarm_id) + "</td></tr>";
    }
    var content = [];
    content[0] = "<div  style='max-width:210px;min-height:100px;max-height:200px;font-size:11px;overflow:hidden;'>" +
            "<div class='iwh'><h4>" + data.nopol + "(" + data.gps_brand + ")</h4></div>" +
            "<table id='tbl_infowindow'>" + str_alarm +
            "<tr><td>Imei</td><td>:</td><td>" + data.imei + "</td></tr>" +
            //  "<tr><td>Imei</td><td>:</td><td>" + data.imei + "</td></tr>" +
            //  "<tr><td>Nama Driver</td><td>:</td><td>" + data.driver_name + "</td></tr>" +
            //  "<tr><td>Phone Driver</td><td>:</td><td>" + data.driver_phone + "</td></tr>" +
            "<tr><td>Tanggal</td><td>:</td><td>" + data.tdate + "</td></tr>" +
            "<tr><td>Koordinat</td><td>:</td><td>" + data.lat + "," + data.lng + "</td></tr>" +
            "<tr><td>Kecepatan</td><td>:</td><td>" + parseInt(data.speed, 10) + " Km/J, Arah(" + dName(data.angle) + ")</td></tr>";
    content[1] = "<tr><td>Lokasi</td><td>:</td><td><div id='address_content' >" + (data.address === "" ? "Query Adress....." : data.address) + "</div></td></tr>";
    content[2] = "</table></div>";
    return content;
};
update_list_gps = function(data) {
    gpsList[data.id] = data;
};
update_gps_address = function(id, address) {
    var gpsObject = gpsList[id];
    if (gpsObject !== null) {
        gpsObject.address = address;
        gpsObject.needGeocoding = false;
    }
};
//Resolve coordinate to Address
get_geocoder = function(latlng) {
    var gObject = gpsList[id];
    if (gObject === null || gObject === 'undefine') {
        //console.log("gObject === null || gObject === 'undefine'");
        return "<h1>Maaf Informasi GPS Tidak Bisa Ditampilkan</h1>";
    }
    return create_iw_content(gObject);

    // var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng, result_type: street_address}, function(results, status) {
        var address = "";
        if (status === google.maps.GeocoderStatus.OK) {
            console.log(results);
            if (results[1]) {
                address = results[1].formatted_address;
                // update_gps_address(id, address);
            } else {
                address = 'No results found';
            }
        } else {
            address = 'Geocoder failed due to: ' + status;
        }
        //console.log("Geocoding Address:" + address);
        $("#address_content").html(address);
    });

};
//Get Info Window
get_infoWindow = function(id) {
    // alert(id);
    var gObject = gpsList[id];
    if (gObject === null || gObject === 'undefine') {
        // console.log("gObject === null || gObject === 'undefine'");
        return "<h1>Maaf Informasi GPS Tidak Bisa Ditampilkan</h1>";
    }
    return create_iw_content(gObject);
};
show_tail_icon = function() {
    if (tail_icon_visible === true) {
        tail_icon_visible = false;
        tail_vh_id = 0;
        clear_tail();
        return;
    }
    if (requestHandlerTail !== null)
        requestHandlerTail.abort();
    clear_tail();
    tail_vh_id = selectedMarkerId;
    requestHandlerTail = $.getJSON('php_script/get_tail.php?', {vh_id: tail_vh_id}, function(objects) {
        init_tail();
        $.each(objects, function(i, data) {
            //console.log(data);
            var path = tail.getPath();
            var latlng = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lng));
            path.push(latlng);
            //console.log(data.tdate+':'+data.id);
        });
        var rev = tail.getPath();
        // rev.reverse();

    });
    tail_icon_visible = true;
};

refresh_gps = function() {
    if (timerGps !== null)
        clearTimeout(timerGps);
    if (requestHandler !== null)
        requestHandler.abort();

    var all = [];
    var online = [];
    var offline = [];
    var total = 0;
    var totalOnline = 0;
    var totalOffline = 0;

    var bounds = new google.maps.LatLngBounds();
    console.log('user_id:' + user_id);
    requestHandler = $.getJSON('php_script/load_gps.php?', {user_id: user_id}, function(objects) {
        //Process Vehicle Group
        $.each(objects.group, function(i, group) {
            all.push({
                id: group.id, level: group.level,
                text: group.text, state: group.state,
                iconCls: group.iconCls, children: []
            });
            online.push({
                id: group.id, level: group.level,
                text: group.text, state: group.state,
                iconCls: group.iconCls, children: []
            });
            offline.push({
                id: group.id, level: group.level,
                text: group.text, state: group.state,
                iconCls: group.iconCls, children: []
            });
        });

        timerGps = setTimeout("refresh_gps();", refreshInterval);

        //Process Vehicle Data
        var currDate = new Date();
        var month = currDate.getMonth() + 1;
        var dateNow = currDate.getFullYear() + "-" + month + "-" + currDate.getDate() + " " + currDate.getHours() + ":" + currDate.getMinutes() + ":" + currDate.getSeconds();

        $.each(objects.childs, function(i, child)
        {
            //Chrome is OK, firefox problem
            //var diff = diff_minute(new Date(), new Date(child.tdate));

            var diff = diff_datetime(child.tdate, dateNow); //in milisecond           
            ////20000 * 60 * 3
            //console.log(child.tdate + " = " + diff);
            if (diff >= 180 || isNaN(diff)) {
                child.status = "off";
            } else {
                if (parseInt(child.acc_state, 10) === 1) {
                    child.status = "on";
                } else if (parseInt(child.acc_state, 10) === 0) {
                    child.status = "stop";
                } else {
                    child.status = "stop";
                }
            }

            //update_list_gps(child);
            gpsList[child.id] = child;
            var latlng = new google.maps.LatLng(parseFloat(child.lat), parseFloat(child.lng));
            if (bound === true) {
                bounds.extend(latlng);
            }
            var marker = markers[child.id];
            var lbl = null;
            //console.log(marker);
            if (marker === null || marker === undefined)
            {
                console.log("marker === null || marker === undefine");
                marker = create_marker2(child.id, latlng, child.icon, child.icon_image, child.angle, child.status);
                lbl = map_label(child.id, child.nopol, marker);
                marker.setMap(map);
                markers[child.id] = marker;
                labels[child.id] = lbl;
            } else {
                console.log("marker !== null || marker !== undefine");
                var icon = create_icon2(child.icon, child.icon_image, child.angle, child.status);
                marker.setIcon(icon);
                marker.setPosition(latlng);
            }

            //Check if Mode Center GPS Active
            if ((center_gps_active === true) && (center_gps_vh_id === child.id)) {
                map.setCenter(latlng);
                var path = polyline.getPath();
                path.push(latlng);
                google.maps.event.trigger(marker, 'click');
                //show_infowindow(child, id, marker);
            }

            for (var i = 0; i < all.length; i++)
            {
                if (all[i].id === child.vh_group) {
                    all[i]['children'].push({
                        id: child.id,
                        level: child.level,
                        text: child.text,
                        state: child.state,
                        iconCls: 'icon-' + child.status,
                        tdate: child.tdate,
                        imei: child.imei,
                        icon: child.icon,
                        lat: child.lat,
                        lng: child.lng,
                        speed: child.speed,
                        angle: child.angle,
                        acc_state: child.acc_state,
                        fuel_cut: child.fuel_cut,
                        batt_level: child.batt_level,
                        signal_gsm: child.signal_gsm,
                        satelite: child.satelite,
                        charge_state: child.charge_state,
                        status: child.status,
                        ododmeter: child.ododmeter,
                        poi: child.poi,
                        address: child.address
                    });
                }
                if ((child.status === "on" || child.status === "stop") && all[i].id === child.vh_group) {
                    totalOnline++;
                    total++;
                    online[i]['children'].push({
                        id: child.id,
                        level: child.level,
                        text: child.text,
                        state: child.state,
                        iconCls: 'icon-' + child.status,
                        tdate: child.tdate,
                        imei: child.imei,
                        icon: child.icon,
                        lat: child.lat,
                        lng: child.lng,
                        speed: child.speed,
                        angle: child.angle,
                        acc_state: child.acc_state,
                        fuel_cut: child.fuel_cut,
                        batt_level: child.batt_level,
                        signal_gsm: child.signal_gsm,
                        satelite: child.satelite,
                        charge_state: child.charge_state,
                        status: child.status,
                        ododmeter: child.ododmeter,
                        poi: child.poi,
                        address: child.address
                    });
                } else if (child.status === "off" && all[i].id === child.vh_group) {
                    totalOffline++;
                    total++;
                    offline[i]['children'].push({
                        id: child.id,
                        level: child.level,
                        text: child.text,
                        state: child.state,
                        iconCls: 'icon-' + child.status,
                        tdate: child.tdate,
                        imei: child.imei,
                        icon: child.icon,
                        lat: child.lat,
                        lng: child.lng,
                        speed: child.speed,
                        angle: child.angle,
                        acc_state: child.acc_state,
                        fuel_cut: child.fuel_cut,
                        batt_level: child.batt_level,
                        signal_gsm: child.signal_gsm,
                        satelite: child.satelite,
                        charge_state: child.charge_state,
                        status: child.status,
                        ododmeter: child.ododmeter,
                        poi: child.poi,
                        address: child.address
                    });
                }
            } //end loop all group
        }); //End loop vehicle data
        //
        //Bound Map to All GPS POsition
        if (bound === true) {
            map.fitBounds(bounds);
            bound = false;
        }

        //Update Tree GPS
        if (editTreeGPS === false) {
            refresh_tree(all, online, offline);
        }

        //Update Tabs GPS    
        tabOnline.tabs('update', {
            tab: tabOnline.tabs('getTab', 0),
            options: {
                title: "All(" + total + ")"
            }
        });
        tabOnline.tabs('update', {
            tab: tabOnline.tabs('getTab', 1),
            options: {
                title: "Online(" + totalOnline + ")"
            }
        });
        tabOnline.tabs('update', {
            tab: tabOnline.tabs('getTab', 2),
            options: {
                title: "Offline(" + totalOffline + ")"
            }
        });
    });

};

map_label = function(id, nopol, marker)
{
    var label = new Label({
        id: id, map: map
    });
    label.bindTo('position', marker, 'position');
    label.set('text', nopol);
    return label;
};
dName = function(a) {
    if ((a >= 337.5) && (a >= 0) && (a <= 22))
        return "Utara";
    if ((a >= 22.5) && (a <= 67))
        return "Timur Laut";
    if ((a >= 67.5) && (a <= 112))
        return "Timur";
    if ((a >= 112.5) && (a <= 157))
        return "Tenggara";
    if ((a >= 157.5) && (a <= 202))
        return "Selatan";
    if ((a >= 202.5) && (a <= 247))
        return "Barat Daya";
    if ((a >= 247.5) && (a <= 292))
        return "Barat";
    if ((a >= 292.5) && (a <= 337))
        return "Barat Laut";
};

clear_trip = function() {
    if (tripReqHandler) {
        tripReqHandler.abort();
    }
    if (trips.length > 0) {
        trackPlayback = [];
    }
    if (tripPolyline) {
        tripPolyline.setMap(null);
        var path = tripPolyline.getPath();
        path = [];
    }
    if (tripMarker) {
        tripMarker.setMap(null);
    }
    if (tripEventMarker) {
        for (i in  tripEventMarker) {
            tripEventMarker[i].setMap(null);
        }
        trackicons = [];
    }
    if (beginTripMarker) {
        beginTripMarker.setMap(null);
    }
    if (endTripMarker) {
        endTripMarker.setMap(null);
    }

};

save_profile = function() {
    $.messager.progress();
    formProfile.form('submit', {
        url: 'php_script/save_profile.php',
        onSubmit: function(param) {
            return true; //$(this).form('validate');
        },
        success: function(result) {
            console.log(result);
            $.messager.progress('close');
            var result = eval('(' + result + ')');
            if (result.errorCode > 0) {
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                $.messager.show({
                    title: 'Success',
                    msg: result.successMsg
                });
                dlgProfile.dialog('close'); // close the dialog
            }
        }
    });
};
edit_profile = function() {
    $.messager.progress();
    $.ajax({
        url: 'php_script/get_profile.php',
        dataType: 'json',
        success: function(data) {
            $.messager.progress('close');
            console.log(data);
            dlgProfile.dialog('open');
            formProfile.form('load', data);
        },
        error: function() {
            $.messager.progress('close');
        }
    });
};
change_password = function(new_password) {
    var new_password = prompt("ketik password", "");
    if (new_password !== null) {
        $.messager.progress();
        $.ajax({
            type: "POST",
            url: "php_script/update_password.php",
            data: {new_password: new_password},
            success: function(result) {
                $.messager.progress('close');
                console.log(result);
                var result = eval('(' + result + ')');
                if (result.errorCode > 0) {
                    $.messager.show({
                        title: 'Error',
                        msg: result.errorMsg
                    });
                } else {
                    $.messager.show({
                        title: 'Success',
                        msg: result.successMsg
                    });
                }

            }
        });
    }
};

create_marker_event = function(data) {
    var markerEvent = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        icon: 'themes/icons/alarm.png'
    });
    google.maps.event.addListener(markerEvent, 'click', function() {
        var content = "<div>Event:" + get_alarm_name(data.alarm_id) + "</br>";
        content += "Date:" + data.tdate + "</br>";
        content += "Speed:" + data.speed + " Km/jam</br>";
        content += "Lat:" + data.lat + "</br>";
        content += "Lng:" + data.lng + "</br>";
        content += "Address:" + data.address + "</div>";
        if (infoWindowTrip !== null)
            infoWindowTrip.close();
        infoWindowTrip = new google.maps.InfoWindow({content: content});
        infoWindowTrip.open(map, markerEvent);
    });
    return markerEvent;
};
polyline_init = function()
{
    polyline = new google.maps.Polyline({
        strokeColor: "#80ff00",
        strokeOpacity: 0.8,
        strokeWeight: 3
    });
    polyline.setMap(map);
};
polyline_addpoint = function(latlng) {
    var path = polyline.getPath();
    path.push(latlng);
};
polyline_clear = function() {
    // if (polyline !== null || polyline !== undefined || polyline !== 'undefined') 
    if (polyline)
    {
        var path = polyline.getPath();
        path.clear();
        path = [];
        polyline.setMap(null);
    }
};
zoomTo = function(latlng) {
    if (latlng !== null)
    {
        map.setCenter(latlng);
        map.setZoom(map.getZoom() + 2);
    }
    return;
};
zoomAll = function() {
    if (markers) {
        var bounds = new google.maps.LatLngBounds();
        for (i in markers) {
            bounds.extend(markers[i].getPosition());
        }
        map.fitBounds(bounds);
    }
};
zoomGroup = function(node) {
    var bounds = new google.maps.LatLngBounds();
    var total = 0;
    $.each(node.children, function(i, child)
    {
        // console.log(child.lat+":"+child.lng);
        var latlng = new google.maps.LatLng(parseFloat(child.lat), parseFloat(child.lng));
        bounds.extend(latlng);
        total++;
    });
    if (total > 0) {
        map.fitBounds(bounds);
    }
};
update_speedometer = function(speed, signal_gsm, satelite, fuel) {
    gaugeSpeed = jQuery("#gauge_speed").gauge({
        min: 0,
        max: 200,
        label: 'SPEED',
        bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    });
    gaugeSpeed.gauge('setValue', speed);

    gaugeFuel = jQuery("#gauge_fuel").gauge({
        min: 0,
        max: 10,
        label: 'BBM',
        bands: [{color: "#ff0000", from: 0, to: 2}, {color: "#FFA500", from: 2, to: 5}, {color: "#FFA500", from: 5, to: 7}, {color: "#00ff00", from: 7, to: 10}]
    });
    gaugeFuel.gauge('setValue', fuel);

    gaugeSignalGsm = jQuery("#gauge_signal_gsm").gauge({
        min: 0,
        max: 10,
        label: 'GSM',
        bands: [{color: "#ff0000", from: 0, to: 2}, {color: "#FFA500", from: 2, to: 5}, {color: "#FFA500", from: 5, to: 7}, {color: "#00ff00", from: 7, to: 10}]
    });
    gaugeSignalGsm.gauge('setValue', signal_gsm);

    gaugeSignalGps = jQuery("#gauge_signal_gps").gauge({
        min: 0,
        max: 10,
        label: 'GPS',
        bands: [{color: "#ff0000", from: 0, to: 2}, {color: "#FFA500", from: 2, to: 5}, {color: "#FFA500", from: 5, to: 7}, {color: "#00ff00", from: 7, to: 10}]
    });
    gaugeSignalGps.gauge('setValue', satelite);
};
select_gps = function(id) {
    selectedMarker = markers[id];
    cboPlaybackId.combogrid('setValue', id);
    if (selectedMarker !== null)
    {
        trip_icon = gpsList[id].icon;
        selectedMarkerId = id;
        map.setCenter(selectedMarker.getPosition());
        map.setZoom(16);
        google.maps.event.trigger(selectedMarker, 'click');
    }
    var pb_vh_id = $('#trip_vh_id');
    if (pb_vh_id !== null) {
        pb_vh_id.combogrid('setValue', selectedMarkerId);
    }
};
show_infowindow = function(id, marker) {
    var gObject = gpsList[id];
    var detilFound = true;
    var content = [];
    var strContent = "";
    if (gObject === null || gObject === undefined) {
        detilFound = false;
        strContent = "<h1>Maaf Informasi GPS Tidak Bisa Ditampilkan</h1>";
    }
    if (detilFound) {

        content = create_iw_content(gObject);
    }


    for (var i = 0; i < content.length; i++) {
        strContent += content[i];
    }
    if (infoWindow !== null)
        infoWindow.close();
    var latlng = new google.maps.LatLng(parseFloat(gObject.lat), parseFloat(gObject.lng));
    marker.setPosition(latlng);
    infoWindow = new google.maps.InfoWindow({content: strContent});
    infoWindow.setPosition(latlng);
    infoWindow.open(map, marker);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        var address = "";
        if (status === google.maps.GeocoderStatus.OK) {
            //console.log(results);
            if (results[0]) {
                address = results[0].formatted_address;
            } else if (results[1]) {
                address = results[1].formatted_address;
            } else if (results[2]) {
                address = results[2].formatted_address;
            } else if (results[3]) {
                address = results[3].formatted_address;
            } else if (results[4]) {
                address = results[4].formatted_address;
            } else if (results[5]) {
                address = results[5].formatted_address;
            } else {
                address = 'No results found';
            }
        } else {
            address = 'Geocoder failed due to: ' + status;
        }
        gpsList[id].address = address;
        var gps = gpsList[id];
        console.log(gps);
        update_info_gps_detil(gps);
        //console.log("Geocoding Address:" + address);

        if (infoWindow !== null)
        {
            // console.log("Not null:"+ content.length);
            if (content.length >= 3)
            {
                console.log("if (content >= 3)");
                strContent = content[0];
                strContent += "<tr><td>Lokasi</td><td>:</td><td><div id='address_content' style='font-size:11px;'>" + address + "</div></td></tr>";
                strContent += content[2];
                infoWindow.setContent(strContent);
            } else {
                // console.log("if (content < 3)");
            }
        } else {
            console.log("if (infoWindow === null)");
        }
    });
};

show_infowindow2 = function(id, marker) {
    var gObject = gpsList[id];
    var detilFound = true;
    var content = [];
    var strContent = "";
    if (gObject === null || gObject === undefined) {
        detilFound = false;
        strContent = "<h1>Maaf Informasi GPS Tidak Bisa Ditampilkan</h1>";
    }
    if (detilFound) {

        content = create_iw_content(gObject);
    }


    for (var i = 0; i < content.length; i++) {
        strContent += content[i];
    }
    if (infoWindow !== null)
        infoWindow.close();
    var latlng = new google.maps.LatLng(parseFloat(gObject.lat), parseFloat(gObject.lng));
    marker.setPosition(latlng);
    infoWindow = new google.maps.InfoWindow({content: strContent});
    infoWindow.setPosition(latlng);
    infoWindow.open(map, marker);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        var address = "";
        if (status === google.maps.GeocoderStatus.OK) {
            //console.log(results);
            if (results[0]) {
                address = results[0].formatted_address;
            } else if (results[1]) {
                address = results[1].formatted_address;
            } else if (results[2]) {
                address = results[2].formatted_address;
            } else if (results[3]) {
                address = results[3].formatted_address;
            } else if (results[4]) {
                address = results[4].formatted_address;
            } else if (results[5]) {
                address = results[5].formatted_address;
            } else {
                address = 'No results found';
            }
        } else {
            address = 'Geocoder failed due to: ' + status;
        }
        gpsList[id].address = address;
        var gps = gpsList[id];
        console.log(gps);
        update_info_gps_detil(gps);
        //console.log("Geocoding Address:" + address);

        if (infoWindow !== null)
        {
            // console.log("Not null:"+ content.length);
            if (content.length >= 3)
            {
                console.log("if (content >= 3)");
                strContent = content[0];
                strContent += "<tr><td>Lokasi</td><td>:</td><td><div id='address_content' style='font-size:11px;'>" + address + "</div></td></tr>";
                strContent += content[2];
                infoWindow.setContent(strContent);
            } else {
                // console.log("if (content < 3)");
            }
        } else {
            console.log("if (infoWindow === null)");
        }
    });
};
create_marker_poi = function(poi_name, icon, lat, lng) {
    var latlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
    var marker = new google.maps.Marker({
        title: poi_name,
        draggable: false,
        position: latlng,
        map: map,
        icon: 'images/poi/' + icon
    });
    google.maps.event.addListener(marker, 'click', function() {
        if (infoWindowPoi !== null)
            infoWindowPoi.close();
        infoWindowPoi = new google.maps.InfoWindow({
            content: "<div>" + poi_name + "</br>" + lat + "/" + lng + "</div>"
        });
        infoWindowPoi.open(map, marker);
    });
    //map.setZoom(18);
    return marker;
};
//Khusus Maidy tracker
create_marker2 = function(id, latlng, icon, icon_image, angle, status) {
    var marker = new google.maps.Marker({
        title: id,
        position: latlng,
        map: map
        , icon: create_icon2(icon, icon_image, angle, status)
    });
    google.maps.event.addListener(marker, 'click', function() {
        selectedMarker = marker;
        selectedMarkerId = id;
        show_infowindow(id, marker);
    });
    return marker;
};

create_marker = function(id, latlng, icon, speed, angle) {
    var marker = new google.maps.Marker({
        title: id,
        position: latlng,
        map: map,
        icon: 'images/gps/' + create_icon(icon, speed, angle)
    });
    google.maps.event.addListener(marker, 'click', function() {
        selectedMarker = marker;
        selectedMarkerId = id;
        show_infowindow(id, marker);
    });
    return marker;
};
clear_marker = function() {
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
        markers.length = 0;
    }

    if (labels) {
        for (i in labels) {
            labels[i].setMap(null);
        }
        labels.length = 0;
    }

    if (polyline) {
        polyline_clear();
    }
};
clear_tracks = function() {
    if (tripEventMarker) {
        for (i in  tripEventMarker) {
            tripEventMarker[i].setMap(null);
        }
        tripEventMarker.length = 0;
    }
    polyline_clear();
    tracks = [];
};
//Khusus Maidry Tracker
create_icon2 = function(icon, icon_image, a, status)
{
    //console.log('Angle:' + a);
    var state = status + '.png';
    var path = 'https://my-iconx.googlecode.com/svn/trunk/gps/';
    if (icon === 'orang') {
        return path + icon + "/orang.png";
    }
    if (icon === 'mobil' || icon === 'motor')
    {
        //  console.log('images/gps/' + icon + "/0-" + state);
        if ((a >= 337.5) || ((a >= 0) && (a <= 22)))
            return path + icon + "/0-" + state;
        if ((a > 22.0) && (a <= 67.0))
            return path + icon + "/45-" + state;
        if ((a > 67.0) && (a <= 112.0))
            return path + icon + "/90-" + state;
        if ((a > 112.0) && (a <= 157.0))
            return path + icon + "/135-" + state;
        if ((a > 157.0) && (a <= 202.0))
            return path + icon + "/180-" + state;
        if ((a > 202.0) && (a <= 247.0))
            return path + icon + "/225-" + state;
        if ((a > 247.0) && (a <= 292.0))
            return path + icon + "/270-" + state;
        if ((a > 292.0) && (a <= 337))
            return path + icon + "/315-" + state;
    }
    return 'images/icon/' + icon_image;
};

create_icon = function(icon, s, a)
{
    var state = 'on.png';
    if (s <= 0)
        state = 'stop.png';
//    if (icon !== 'motor' && icon !== 'mobil') {
//        icon = 'mobil';
//    }
    if ((a >= 337.5) || ((a >= 0) && (a <= 22)))
        return icon + "/0-" + state;
    if ((a >= 22.5) && (a <= 67))
        return icon + "/45-" + state;
    if ((a >= 67.5) && (a <= 112))
        return icon + "/90-" + state;
    if ((a >= 112.5) && (a <= 157))
        return icon + "/135-" + state;
    if ((a >= 157.5) && (a <= 202))
        return icon + "/180-" + state;
    if ((a >= 202.5) && (a <= 247))
        return icon + "/225-" + state;
    if ((a >= 247.5) && (a <= 292))
        return icon + "/270-" + state;
    if ((a >= 292.5) && (a <= 337))
        return icon + "/315-" + state;
};
/*******************************************/
/*          POLYGON /GEOFENCE              */
/*******************************************/
//parse geofence from selected datarow

load_geofence = function(vh_id) {
    console.log("Load Geofence,vh_id:" + vh_id);
    clear_geofence();
    if (requestHandler !== null) {
        requestHandler.abort();
    }
    requestHandler = $.getJSON('php_script/get_geofence.php', {vh_id: vh_id}, function(data) {
        console.log(data);
        var html = "";
        var no = 1;
        html = "<table class='tblgeofence'><tr><td class='w100'>Nama</td><td class='w100'>Operate</td></tr>";
        $.each(data, function(i, item) {
            console.log(item);
            draw_geofence(item.id, item.vh_id, item.name, item.geofence);
            html = html + "<tr><td>" + item.name + "</td><td><a href='#' onClick='show_poi_control();'>POI</a><a href='#' onClick='del_geofence(" + item.id + ");'>Del</a>&nbsp;|&nbsp;<a href='#' onClick='edit_geofence(" + item.id + ");'>Edit</a></td></tr>";
            //html = html + "<tr id='row_"+ no +"'><td><input type='text></td><td><a href='#' onClick='del_geofence(" + item.id + ");'>Del</a>&nbsp;|&nbsp;<a href='#' onClick='edit_geofence(" + item.id + ");'>Edit</a></td></tr>";
            no++;
        });
        html = html + "</table>";
        $("#table_geofence").html(html);
    });
};
draw_geofence = function(id, vh_id, name, arr) {
    var path = [];
    var coor = arr.split(",");
    for (i = 0; i < coor.length; i++) {
        var ll = coor[i].split(" ");
        var lat = parseFloat(ll[0]);
        var lng = parseFloat(ll[1]);
        path.push(new google.maps.LatLng(lat, lng));
    }
    var p = new google.maps.Polygon({
        paths: path,
        editable: false,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map
    });
    var pObject = {
        id: id,
        vh_id: vh_id,
        name: name,
        state: '',
        polygon: p
    };
    polygons[id] = pObject;
};
find_geofence = function(id) {
    var p = null;
//    if (polygons) {
//        for (i in polygons) {
//            if (polygons[i].id === id) {
//                p = polygons[i];
//            } else {
//                polygons[i].polygon.setVisible(false);
//            }
//        }
    //    }
    return p;
};
edit_geofence = function() {
    if (geofenceEdit.edit_mode === true) {
        alert('Edit Geofence Active..');
        return;
    }
    var node = treeGeofence.tree('getSelected');
    console.log(node);
    if (node !== null)
    {
        $("#enter_alarm").prop('checked', node.exit_alarm === 1 ? true : false);
        $("#exit_alarm").attr('checked', node.exit_alarm === 1 ? 'checked' : '');
        dlgGeofence.dialog('open');
        formGeofence.form('load', {
            id: node.id,
            name: node.text
        });
        var bounds = new google.maps.LatLngBounds();
        var coordinats = node.geofence.split(",");
        var path = [];
        for (var i = 0; i < coordinats.length; i++)
        {
            var ll = coordinats[i].split(" ");
            var latlng = new google.maps.LatLng(parseFloat(ll[0]), parseFloat(ll[1]));
            path.push(latlng);
            bounds.extend(latlng);
        }
        map.fitBounds(bounds);
        geofenceEdit.edit_mode = true;
        geofenceEdit.id = node.id;
        geofenceEdit.name = node.text;
        geofenceEdit.description = node.description;
        geofenceEdit.vh_id = node.vh_id;
        geofenceEdit.name = node.text;
        geofenceEdit.enter_alarm = node.enter_alarm;
        geofenceEdit.exit_alarm = node.exit_alarm;
        geofenceEdit.polygon = new google.maps.Polygon({
            paths: path,
            editable: true,
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map: map
        });
    }
};
clear_geofence = function() {
    if (geofenceEdit.polygon !== null) {
        geofenceEdit.polygon.setPath([]);
        geofenceEdit.polygon.setMap(null);
    }
    clickMapHandler = null;
    geofenceEdit.edit_mode = false;
};
add_geofence = function() {
    clear_geofence();
    dlgGeofence.dialog('open');
    formGeofence.form('load', {
        vh_id: selectedMarkerId
    });
    //Clear existing previous tool
    geofenceEdit.polygon = new google.maps.Polygon({
        map: map,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        draggable: true,
        editable: true,
        geodesic: true
    });
    clickMapHandler = google.maps.event.addListener(map, 'click', add_geofence_point);
};
function add_geofence_point(event) {
    var path = geofenceEdit.polygon.getPath();
    path.push(event.latLng);
}
close_geofence_form = function() {
    dlgGeofence.dialog('close');
    geofenceEdit.edit_mode = false;
    clear_geofence();
};
save_geofence = function() {
    if (geofenceEdit.polygon !== null)
    {
        var path = geofenceEdit.polygon.getPath(); //.getArray();
        var arr = path.getArray();
        var latlng = [];
        if (arr) {
            for (i in arr) {
                latlng.push(arr[i].lat() + " " + arr[i].lng());
            }
        }
        console.log(latlng);
        formGeofence.form('load', {
            geofence: latlng
        });
        $.messager.progress();
        formGeofence.form('submit', {
            url: 'php_script/save_geofence.php',
            success: function(result) {
                $.messager.progress('close');
                var result = eval('(' + result + ')');
                if (result.errorCode > 0) {

                    $.messager.show({
                        title: 'Error',
                        msg: result.errorMsg
                    });
                } else {
                    $.messager.show({
                        title: 'Success',
                        msg: result.successMsg
                    });
                }
            }
        });
    }
};

del_geofence = function(id) {
    $.post('php/del_polygon.php', {id: id},
    function(result) {
        load_geofence();
        alert(result);
    }
    );
};
init_sound = function() {
    audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'sound/siren.wav');
    audioElement.setAttribute('autoplay', 'autoplay');
    audioElement.addEventListener('ended', function() {
        // Wait 500 milliseconds before next loop
        if (currentLoop < maxLoop) {
            currentLoop++;
            setTimeout(function() {
                audioElement.play();
            }, 500);
        }
    }, false);
};
stop_sound = function() {
    currentLoop = 6;
    audioElement.pause();
    audioElement.currentTime = 0;
};
play_sound = function() {
    //var sound=$('#enable_sound').val($(this).is(':checked'));
    var checked = document.getElementById("enable_sound").checked;
    console.log(checked);
    if (checked !== true) {
        return;
    }
    if (audioElement === null) {
        init_sound();
    }
    if (currentLoop < maxLoop) {
        return;
    }
    currentLoop = 0;
    audioElement.play();
};
refresh_poi = function() {
    treePoi.tree({
        url: 'php_script/json_data_poi.php',
        checkbox: true,
        cascadeCheck: true,
        dnd: false,
        onClick: function(e) {
            var icon = icons[e.id];
            if (icon !== undefined) {
                map.setCenter(icon.getPosition());
                map.setZoom(18);
                google.maps.event.trigger(selectedMarker, 'click');
            }
        },
        onCheck: function(e) {
            // console.log(e);
            switch (e.level)
            {
                case 1:
                    $.each(e.children, function(i, item)
                    {
                        if (item.level === 2)
                        {
                            var icon = icons[i];
                            switch (e.checked) {
                                case true:
                                    if (icon !== undefined) {
                                        icon.setMap(null);
                                    }
                                    break;
                                case false:
                                    if (icon === undefined)
                                    {
                                        icon = create_marker_poi(item.poi_name, item.icon, item.lat, item.lng);
                                        icons[item.id] = icon;
                                    } else {
                                        icon.setMap(map);
                                    }
                                    break;
                            }

                        }
                    });
                    break;
                case 2:
                    var icon = icons[e.id];
                    switch (e.checked) {
                        case true:
                            if (icon !== undefined) {
                                icon.setMap(null);
                            }
                            break;
                        case false:
                            if (icon === undefined)
                            {
                                icon = create_marker_poi(e.poi_name, e.icon, e.lat, e.lng);
                                icons[e.id] = icon;
                            } else {
                                icon.setMap(map);
                            }
                            break;
                    }
                    break;
            }
        },
        animate: false
    });
};
function displayTime() {
    //var elt = document.getElementById("clock");  // Find element with id="clock"
    var now = new Date(); // Get current time
    jam.html(now.toLocaleTimeString()); // Make elt display it
    setTimeout(displayTime, 1000); // Run again in 1 second
}
//refresh_geofence = function() 
//{
//    treeGeofence.tree({
//        url: 'php_script/json_data_geofence.php',
//        checkbox: 'true',
//        dnd: true,
//        onClick: function(node) {
//            //select_geofence(node.id);
//        },
//        onCheck: function(e) {                              }
//        },
//        onContextMenu: function(e, node) {
//            e.preventDefault();
//            $(this).tree('select', node.target);
//            $('#mm_geofence').menu('show', {
//                left: e.pageX,
//                top: e.pageY
//            });
//        },
//        onDrop: function(targetNode, source, point) {
//            var targetId = $(target).tree('getNode', targetNode).id;
//            $.ajax({
//                url: 'target.update.php',
//                type: 'post',
//                dataType: 'json',
//                data: {
//                    id: source.id,
//                    targetId: targetId,
//                    point: point
//                }
//            });
//        }
//    });
//};
control_gps = function(cmd) {
    console.log(cmd);
    switch (cmd) {
        case 'centergps':
            if (selectedMarker !== null) {
                center_gps_active = !center_gps_active;
                $("#btn_centergps").toggleClass("button_red", center_gps_active);
                if (center_gps_active === false) {
                    center_gps_marker = null;
                    center_gps_vh_id = 0;
                    polyline.setMap(null);
                } else {
                    center_gps_marker = selectedMarker;
                    center_gps_vh_id = selectedMarkerId;
                    map.setCenter(selectedMarker.getPosition());
                    polyline_init();
                }
            } else {
                alert("Pilih GPS Lebih Dulu...");
            }
            break;
        case 'engineon':
            break;
        case 'engineoff':
            break;
        case 'position':
            break;
        case 'track':
            break;
        case 'playback':
            window.open('playback.php?id=' + selectedMarkerId, '_newtab');
            break;
        case 'setgeofence':
            window.open('geofence.php?id=' + selectedMarkerId, '_newtab');
            break;
    }
};
update_info_gps_detil = function(data) {
    console.log(data);
    var content =
            "<table>" +
            "<tr><td style='width:90px;'>Imei</td><td>:</td><td>" + data.imei + "</td></tr>" +
            "<tr><td style='width:90px;'>Tanggal</td><td>:</td><td>" + data.tdate + "</td></tr>" +
            "<tr><td style='width:90px;'>Status</td><td>:</td><td>" + get_speed_state(parseInt(data.speed, 10)) + "</td></tr>" +
            "<tr><td style='width:90px;'>Nomor GSM </td><td>:</td><td>" + data.phone + "</td></tr>" +
            "<tr><td style='width:90px;'>Nama Drive</td><td>:</td><td>" + data.driver_name + "</td></tr>" +
            "<tr><td style='width:90px;'>HP Driver</td><td>:</td><td>" + data.driver_phone + "</td></tr>" +
            "<tr><td style='width:90px;'>Status ACC</td><td>:</td><td>" + get_acc_state(parseInt(data.acc_state, 10)) + "</td></tr>" +
            "<tr><td style='width:90px;'>Fuel Cut</td><td>:</td><td>" + get_fuel_cut_state(parseInt(data.fuel_cut, 10)) + "</td></tr>" +
            "<tr><td style='width:90px;'>Signal GSM</td><td>:</td><td>" + get_signal_gsm(parseInt(data.signal_gsm, 10)) + "</td></tr>" +
            "<tr><td style='width:90px;'>Power GPS</td><td>:</td><td>" + get_charge_state(parseInt(data.charge_state, 10)) + "</td></tr>" +
            "<tr><td>Koordinat</td><td>:</td><td>" + data.lat + "," + data.lng + "</td></tr>" +
            "<tr><td>Jarak Tempuh</td><td>:</td><td>" + data.odometer + " Km</td></tr>" +
            "<tr><td>Lokasi</td><td>:</td><td><div id='iw_content'>" + data.address + "</div></td></tr>" +
            "<tr><td>Kecepatan</td><td>:</td><td>" + data.speed + " Km/Jam, Arah " + data.angle + "&deg; (" + dName(data.angle) + ")</td></tr>" +
            "</table>";
    panelInfoGps.html(content);
};
/*
 * refresh_tree
 * fungsi ini dipanggil oleh refresh_gps, setiap gps update maka tree gps juga akan diupdate
 * @param {type} jsonAll (Parameter semua gps)
 * @param {type} jsonOnline (Parameter gps yang online saja)
 * @param {type} jsonOffline (Paramter gps yang offline saja)
 * @returns {undefined}
 */
refresh_tree = function(all, online, offline) {
    treeGps.tree({
        data: all,
        /*checkbox: 'false',*/
        dnd: false,
        onClick: function(node) {

            // console.log(node);
            if (node.level === 1) {
                zoomGroup(node);
            } else if (node.level === 2) {
                //console.log(node);
                nodeTree = node;
                console.log(node);
                //cboPlaybackId.combotree('setValue',node.id);
                update_speedometer(node.speed, node.signal_gsm, node.satelite, 0);
                select_gps(node.id);
            }
        },
        onCheck: function(e) {
        },
        animate: false,
        onContextMenu: function(e, node) {
            e.preventDefault();
            //console.log(node);
            editTreeGPS = true;
            switch (parseInt(node.level, 10)) {
                case 1:
                    $("#mnu_edit_gps").hide();
                    $("#mnu_edit_group").show();
                    $(this).tree('select', node.target);
                    $('#mm_gps').menu('show', {
                        left: e.pageX,
                        top: e.pageY,
                        onClick: function(item) {
                            // console.log(item);
                            var val = prompt("Enter Group Name", "");
                            if (val !== null) {
                                $.ajax({
                                    dataType: "json",
                                    type: "POST",
                                    url: 'php_script/update_tree_group.php',
                                    data: {group_id: node.id, new_group: val},
                                    success: function(data) {
                                        // console.log(data);
                                        var nodex = $('#treeGps').tree('getSelected');
                                        if (nodex) {
                                            $('#treeGps').tree('update', {
                                                target: nodex.target,
                                                text: val
                                            });
                                        }
                                    }
                                });
                            }
                        },
                        onHide: function() {
                            editTreeGPS = false;
                        }
                    });
                    break;
                case 2:
                    $("#mnu_edit_group").hide();
                    $("#mnu_edit_gps").show();
                    $(this).tree('select', node.target);
                    $('#mm_gps').menu('show', {
                        left: e.pageX,
                        top: e.pageY,
                        onClick: function(item) {
                            // console.log(item);
                            var val = prompt("Enter Vehicle Name", node.text);
                            if (val !== null) {
                                if (val.trim() !== "") {
                                    $.ajax({
                                        dataType: "json",
                                        type: "POST",
                                        url: 'php_script/update_tree_gps.php',
                                        data: {vh_id: node.id, new_nopol: val},
                                        success: function(data) {
                                            // console.log(data);
                                            var nodex = $('#treeGps').tree('getSelected');
                                            if (nodex) {
                                                $('#treeGps').tree('update', {
                                                    target: nodex.target,
                                                    text: val
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                        },
                        onHide: function() {
                            editTreeGPS = false;
                        }
                    });
                    break;
            }
        },
        onDrop: function(targetNode, source, point) {
            //console.log(source);
            var targetId = treeGps.tree('getNode', targetNode).id;
            $.ajax({
                url: 'php_script/update_group.php',
                type: 'post',
                dataType: 'json',
                data: {
                    id: source.id,
                    parent_id: targetId,
                    point: point
                }
            });
        }
    });
    treeGpsOnline.tree({
        data: online,
        /*checkbox: 'false',*/
        dnd: false,
        onClick: function(node) {
            //console.log(node);
            //if (typeof(node.children) !== 'undefined') {
            if (node.level === 1) {
                //console.log("Zoom Group");
                zoomGroup(node);
            } else if (node.level === 2) {
                //console.log(node);
                nodeTree = node;
                update_speedometer(node.speed, node.signal_gsm, node.satelite, 0);
                select_gps(node.id);
                //update_info_gps_detil(node);
            }
        },
        onCheck: function(e) {

        },
        animate: false,
        onContextMenu: function(e, node) {
            if (node.text.indexOf('Group') === -1)
            {
                e.preventDefault();
                $(this).tree('select', node.target);
                $('#mm_gps').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            } else {
                e.preventDefault();
                $(this).tree('select', node.target);
                $('#mm_gps').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        },
        onDrop: function(targetNode, source, point) {
            //console.log(source);
            var targetId = treeGpsOnline.tree('getNode', targetNode).id;
            $.ajax({
                url: 'php_script/update_group.php',
                type: 'post',
                dataType: 'json',
                data: {
                    id: source.id,
                    parent_id: targetId,
                    point: point
                }
            });
        }
    });
    treeGpsOffline.tree({
        data: offline,
        /*checkbox: 'false',*/
        dnd: false,
        onClick: function(node) {
            //console.log(node);
            //if (typeof(node.children) !== 'undefined') {
            if (node.level === 1) {
                //console.log("Zoom Group");
                zoomGroup(node);
            } else if (node.level === 2) {
                //console.log(node);
                nodeTree = node;
                update_speedometer(node.speed, node.signal_gsm, node.satelite, 0);
                select_gps(node.id);
                //update_info_gps_detil(node);
            }
        },
        onCheck: function(e) {
            //console.log(e);
//                                var selected_nodes = $("#treeVehicle").tree('getChecked');
//                                var selected_gps = [];
//                                var str = "";
//                                for (var i = 0; i < selected_nodes.length; i++) {
//                                    selected_gps.push(selected_nodes[i].id);
//                                }
//
//                                if (selected_gps.length > 0) {
//                                    //GPS.update_vehicle_marker(selected_gps);
//                                } else {
//                                  //  GPS.clear_marker();
            //                                }
        },
        animate: false,
        onContextMenu: function(e, node) {
            if (node.text.indexOf('Group') === -1)
            {
                e.preventDefault();
                $(this).tree('select', node.target);
                $('#mm_gps').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            } else {
                e.preventDefault();
                $(this).tree('select', node.target);
                $('#mm_gps').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        },
        onDrop: function(targetNode, source, point) {
            //console.log(source);
            var targetId = treeGpsOffline.tree('getNode', targetNode).id;
            $.ajax({
                url: 'php_script/update_group.php',
                type: 'post',
                dataType: 'json',
                data: {
                    id: source.id,
                    parent_id: targetId,
                    point: point
                }
            });
//            var targetId = $(target).tree('getNode', targetNode).id;
//            $.ajax({
//                url: 'target.update.php',
//                type: 'post',
//                dataType: 'json',
//                data: {
//                    id: source.id,
//                    targetId: targetId,
//                    point: point
//                }
            //            });
        }
    });
};
/*
 * clear_prev_layout
 * @returns {undefined}
 */
clear_prev_layout = function() {
    if (leftLayout !== null) {
        layout.layout('remove', 'west');
    }
    if (rightLayout !== null) {
        layout.layout('remove', 'east');
    }

    if (centerLayout !== null) {
        layout.layout('remove', 'center');
    }
};
/*
 * Add Layout dengan mengembalikan object panel
 * @param {type} region
 * @param {type} width
 * @param {type} title
 * @param {type} collapsible
 * @param {type} buttons
 * @param {type} _url
 * @returns {unresolved}
 */
add_layout2 = function(region, width, title, collapsible, buttons, _url) {
    layout.layout('add', {
        href: _url,
        region: region,
        width: width,
        title: title,
        split: true,
        tools: buttons,
        collapsible: collapsible
    });
    return layout.layout('panel', region);
};
/*
 * Add Tab
 * @param {type} id
 * @param {type} iconCls
 * @param {type} title
 * @param {type} url
 * @param {type} closable
 * @returns {undefined}
 */
add_tab = function(id, iconCls, title, url, closable) {
    mainTabs.tabs('add', {
        id: id,
        title: title,
        href: url,
        iconCls: iconCls,
        closable: closable
    });
};
add_tab2 = function(id, iconCls, title, content, closable) {
    mainTabs.tabs('add', {
        id: id,
        title: title,
        content: content,
        iconCls: iconCls,
        closable: closable
    });
};
add_tabreport = function(id, iconCls, title, url, closable) {
    reportTabs.tabs('add', {
        id: id,
        title: title,
        href: url,
        iconCls: iconCls,
        closable: closable
    });
};
show_logout_form = function() {
    var form = $("<div style='padding:20px'><h3>Are You Sure Logout ?</h3></div>");
    form.dialog({
        title: 'Logout Confirm', width: 400, height: 150, closed: false, cache: false, modal: true,
        buttons: [{
                text: 'Logout', iconCls: 'icon-ok',
                handler: function() {
                    window.location = "php_script/do_logout.php";
                }
            },
            {
                text: 'Cancel', iconCls: 'icon-cancel',
                handler: function() {
                    form.dialog('close');
                }
            }]
    });
};
//tree_add_poi = function() {
//    dlgPoi.dialog('open');
//};
//tree_edit_poi = function() {
//    var node = treePoi.tree('getSelected');
//    console.log(node);
//    if (node === null || node === 'undefined') {
//        alert('Pilih Poi');
//        return;
//    }
//    dlgPoi.dialog('open');
//    formPoi.form('load', {
//        poi_name: node.text,
//        lat: node.imei,
//        lng: node.phone,
//        id: node.id,
//        mode: 'edit'
//    });
//};
/*
 * User Manager Add,Edit,Delete
 * @returns {undefined}
 */

/****** Admin POI *******/

//add_poi = function() {
//    dlgPoi.dialog('open');
//    formPoi.form('clear');
//    poi = new google.maps.Marker({
//        draggable: true,
//        animation: google.maps.Animation.DROP,
//        position: map.getCenter(),
//        map: map
//    });
//    google.maps.event.addListener(poi, 'dragend', function()
//    {
//        formPoi.form('load', {
//            poi_lat: poi.getPosition().lat(),
//            poi_lng: poi.getPosition().lng()
//        });
//    });
//};
//edit_poi = function() {
//    var row = gridPoi.datagrid('getSelected');
//    console.log(row);
//    if (row === null || row === 'undefined') {
//        alert('Pilih Poi');
//        return;
//    }
//    dlgPoi.dialog('open');
//    formPoi.form('load', row);
//};
change_image = function(img) {
    poi_image_save = img + ".png";
    if (poi !== null) {
        poi.setIcon("images/poi/" + img + ".png");
    }
    console.log("images/poi/" + img + ".png");
    document.getElementById("poi_image").src = "images/poi/" + img + ".png";
};
add_poi_tree = function() {
    dlgPoi.dialog('open');
    formPoi.form('clear');
    if (poi !== null) {
        poi.setMap(null);
    }
    poi = new google.maps.Marker({
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: map.getCenter(),
        map: map
    });
    formPoi.form('load', {
        mode: 'add',
        poi_lat: poi.getPosition().lat(),
        poi_lng: poi.getPosition().lng()
    });
    google.maps.event.addListener(poi, 'dragend', function()
    {
        formPoi.form('load', {
            poi_lat: poi.getPosition().lat(),
            poi_lng: poi.getPosition().lng()
        });
    });
};
edit_poi_tree = function() {
    var node = treePoi.tree('getSelected');
    if (node === null || node === 'undefined') {
        alert('Pilih Poi');
        return;
    }
    var obj = {
        id: node.id,
        poi_name: node.poi_name,
        poi_lat: node.lat,
        poi_lng: node.lng,
        mode: 'edit'
    };
    poi = selectedPoi;
    document.getElementById("poi_image").src = "images/poi/" + node.icon;
    dlgPoi.dialog('open');
    formPoi.form('load', obj);
};
delete_poi_tree = function() {
    var node = treePoi.tree('getSelected');
    if (node === null || node === 'undefined') {
        alert('Pilih Poi');
        return;
    }
    var x = confirm('Delete POI?');
    if (x === true) {
        $.messager.progress();
        $.ajax({
            type: "POST",
            url: 'php_script/save_poi.php',
            data: {
                mode: 'delete',
                id: node.id
            },
            success: function(result) {
                $.messager.progress('close');
                console.log(result);
                var result = eval('(' + result + ')');
                if (result.errorCode > 0) {
                    $.messager.show({
                        title: 'Error',
                        msg: result.errorMsg
                    });
                } else {
                    $.messager.show({
                        title: 'Success',
                        msg: result.successMsg + '|' + result.sql
                    });
                    refresh_poi();
                    dlgPoi.dialog('close'); // close the dialog
                }
            },
            error: function() {
                $.messager.progress('close');
            }

        });
    }
};
save_poi = function() {
    $.messager.progress();
    formPoi.form('submit', {
        url: 'php_script/save_poi.php',
        onSubmit: function(param) {
            param.poi_image = poi_image_save;
            return true; //$(this).form('validate');
        },
        success: function(result) {
            $.messager.progress('close');
            console.log(result);
            var result = eval('(' + result + ')');
            if (result.errorCode > 0) {
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                $.messager.show({
                    title: 'Success',
                    msg: result.successMsg
                });
                refresh_poi();
                dlgPoi.dialog('close');
            }
        }
    });
};
/********** End Admin POI *********/

/****** Admin GPS *******/

/********** End Admin GPS *********/
//add_gps = function() {
//    dlgGps.dialog('open');
//};
//edit_gps = function() {
//    var node = treeGps.tree('getSelected');
//    console.log(node);
//    if (node === null || node === 'undefined') {
//        alert('Pilih GPS');
//        return;
//    }
//    dlgGps.dialog('open');
//    formGps.form('load', {
//        nopol: node.text,
//        imei: node.imei,
//        phone: node.phone,
//        user_id2: node.user_id,
//        id: node.id,
//        mode: 'edit'
//    });
//};
//show_form_playback = function() {
//    //Remove Previous East Layout
//    // layout.layout('remove', 'east');
//    //Set Map Mode to Playback
//    change_map_mode('playback');
//    var buttons = [
//        {
//            text: 'Clear Track',
//            iconCls: 'icon-close',
//            handler: function() {
//                layout.layout('remove', 'east');
//                rightLayout = null;
//                change_map_mode('live');
//            }
//        }];
//    //Recreate east layout
//    rightLayout = add_layout2('east', 350, 'Playback GPS', false, buttons, 'php_script/playback_form.php');
//};
//show_form_poi = function() {
//    //Remove Previous East Layout
//    // layout.layout('remove', 'east');
//    //Set Map Mode to Playback
//    //change_map_mode('playback');
//    var buttons = [
//        {
//            text: 'Clear Track',
//            iconCls: 'icon-close',
//            handler: function() {
//                layout.layout('remove', 'east');
//                rightLayout = null;
//                change_map_mode('live');
//            }
//        }];
//    //Recreate east layout
//    rightLayout = add_layout2('east', 350, 'Playback GPS', false, buttons, 'php_script/poi_form.php');
//
//};
//show_form_geofence = function() {
//    //Remove Previous East Layout
//    // layout.layout('remove', 'east');
//    //Set Map Mode to Playback
//    //change_map_mode('playback');
//    var buttons = [
//        {
//            text: 'Clear Geofence',
//            iconCls: 'icon-close',
//            handler: function() {
//                layout.layout('remove', 'east');
//                rightLayout = null;
//                change_map_mode('live');
//            }
//        }];
//    //Recreate east layout
//    rightLayout = add_layout2('east', 350, 'Geofence GPS', false, buttons, 'php_script/geofence_form.php');
//
//};
//show_form_gps = function() {
//    var dlg = $("<div style='padding:20px'></div>").load('php_script/form_gps.php', function() {
//        dlg.dialog({
//            title: ' Add GPS ', iconCls: 'icon-save',
//            width: 350, height: 365, closed: false, cache: false, modal: true,
//            buttons: [{
//                    text: 'Save',
//                    iconCls: 'icon-save',
//                    handler: function() {
//                        $.messager.progress();	// display the progress bar
//                        $('#form_gps').form('submit', {
//                            url: 'php_script/save_gps.php',
//                            onSubmit: function() {
//                                return true;	// return false will stop the form submission
//                            },
//                            success: function() {
//                                $.messager.progress('close');	// hide progress bar while submit successfully
//                            }
//                        });
//                    }
//                },
//                {
//                    text: 'Cancel',
//                    iconCls: 'icon-cancel',
//                    handler: function() {
//                        this.close();
//                    }
//                }]
//        });
//    });
//};
//set_speedometer_value = function(val) {
//    gaugeSpeedometer.gauge('setValue', val);
//}; 
goto = function(page) {
    switch (page) {
        case 'live':
            clear_prev_layout();
            var tab = mainTabs.tabs('getTab', 'Live Data GPS');
            if (tab !== null) {
                mainTabs.tabs('select', 'Live Data GPS');
                return;
            }
            add_tab('tab_live_gps', 'icon-map', 'Live Data GPS', 'php_script/table_live_data_gps.php', true);
            break;
        case 'map':
            clear_prev_layout();
            var tab = mainTabs.tabs('getTab', 'Google Map');
            if (tab !== null) {
                mainTabs.tabs('select', 'Google Map');
                return;
            }
            add_tab('tab_map', 'icon-map', 'Google Map', 'php_script/map_form.php', true);
            //refresh_gps();
            break;
        case 'playback':
            leftLayout.load('php_script/form_playback.php', function() {
                init_map();
                stop_timer();
            });
            break;
        case 'tripreport':
            var tab = reportTabs.tabs('getTab', 'Trip Report');
            if (tab !== null) {
                reportTabs.tabs('select', 'Trip Report');
                return;
            }
            add_tabreport('tab_trip', 'icon-report', 'Trip Report', 'php_script/table_trip_report.php?vh_id=' + selectedMarkerId, true);
            var p = layout2.layout('panel', 'south');
            if (p.panel('options').collapsed === true) {
                layout2.layout('expand', 'south');
                $("#chk_panel_trip").attr("checked", true);
            }

            //clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Trip Report', false, '', 'php_script/table_trip_report.php');
            break;
        case 'hourreport':
            var tab = reportTabs.tabs('getTab', 'Hour Meter Report');
            if (tab !== null) {
                reportTabs.tabs('select', 'Hour Meter Report');
                return;
            }
            add_tabreport('tab_hour', 'icon-report', 'Hour Meter Report', 'php_script/table_hour_report.php?vh_id=' + selectedMarkerId, true);
            layout2.layout('expand', 'south');
            if ($("#panel_trip_report").panel("options").collapsed === true) {
                $("#chk_panel_trip").attr("checked", true);
            }
            //centerLayout = add_layout2('center', 180, 'Trip Report', false, '', 'php_script/table_trip_report.php');
            break;
        case 'speedreport':
            //clear_prev_layout();
            add_tab('tab_speed', 'icon-report', 'Speed Report', 'php_script/table_trip_report_speed.php', true);
            //centerLayout = add_layout2('center', 180, 'Trip Report By Speed', false, '', 'php_script/table_trip_report_speed.php');
            break;
        case 'fuelreport':
            var tab = reportTabs.tabs('getTab', 'Fuel Report');
            if (tab !== null) {
                reportTabs.tabs('select', 'Fuel Report');
                return;
            }
            add_tabreport('tab_fuel', 'icon-report', 'Fuel Report', 'php_script/table_fuel_report.php', true);
            //layout2.layout('expand', 'south');
            if ($("#panel_trip_report").panel("options").collapsed === true) {
                $("#chk_panel_trip").attr("checked", true);
            }
//clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Trip Report By Fuel Consumtion', false, '', 'php_script/table_trip_report_fuel.php');
            break;
        case 'parkingreport':
            add_tab('tab_parking', 'icon-report', 'Parking Report', 'php_script/table_trip_report_parking.php', true);
            //clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Trip Report By Fuel Consumtion', false, '', 'php_script/table_trip_report_parking.php');
            break;
        case 'alarmreport':
            add_tab('tab_alarm', 'icon-report', 'Alarm Report', 'php_script/table_trip_report_alarm.php', true);
            //clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Trip Report By Fuel Consumtion', false, '', 'php_script/table_trip_report_alarm.php');
            break;
        case 'distancereport':
            add_tab('tab_distance', 'icon-report', 'Distance Report', 'php_script/table_trip_report_distance.php', true);
            //clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Trip Report By Fuel Consumtion', false, '', 'php_script/table_trip_report_distance.php');
            break;
        case 'user':
            var tab = mainTabs.tabs('getTab', 'Edit Data User');
            if (tab !== null) {
                mainTabs.tabs('select', 'Edit Data User');
                return;
            }
            add_tab('tab_user', 'icon-map', 'Edit Data User', 'php_script/table_user.php', true);
            //centerLayout = add_layout2('center', 180, 'Manajemen Data User', false, '', 'php_script/table_user.php');
            break;
        case 'gps':
            var tab = mainTabs.tabs('getTab', 'Edit Data GPS');
            if (tab !== null) {
                mainTabs.tabs('select', 'Edit Data GPS');
                return;
            }
            add_tab('tab_user', 'icon-map', 'Edit Data GPS', 'php_script/table_gps.php', true);
            // clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Manajemen Data GPS', false, '', 'php_script/table_gps.php');
            break;
        case 'poi':
            add_tab('tab_poi', 'icon-poi', 'Manajemen Data POI', 'php_script/table_poi.php', true);
            //clear_prev_layout();
            //centerLayout = add_layout2('center', 180, 'Manajemen Data POI', false, '', 'php_script/table_poi.php');
            break;
    }
};
function open_playback(url)
{
    var win = window.open(url, '_blank');
    win.focus();
}
add_group = function(id) {
    var group_name = $('#' + id).val();
    $.getJSON('php_script/add_group.php', {user_id: user_id, vh_group: group_name}, function(data) {
        //console.log(data);
        var root1 = treeGps.tree();
        var node = treeGps.tree("append", {
            parent: root1.target,
            data: [{
                    id: data.id,
                    level: 1,
                    text: group_name,
                    iconCls: 'icon-folder',
                    state: 'open'
                }]
        });
        refresh_gps();
    });
};
del_group = function(id) {
    switch (id)
    {
        case 'groupAll':
            var node = treeGps.tree('getSelected');
            console.log(node);
            $.getJSON('php_script/del_group.php', {group_id: node.id}, function(data) {
                console.log(data);
                if (data.errorCode === 0) {
                    console.log("Delete Group Success....");
                    treeGps.tree("remove", node.target);
                    refresh_gps();
                }
            });
            break;
        case 'groupOnline':
            var node = treeGpsOnline.tree('getSelected');
            $.getJSON('php_script/del_group.php', {group_id: node.id}, function(data) {
                if (data.errorCode === 0) {
                    treeGpsOnline.tree("remove", node.target);
                    refresh_gps();
                }
            });
            break;
        case 'groupOffline':
            var node = treeGpsOffline.tree('getSelected');
            $.getJSON('php_script/del_group.php', {group_id: node.id}, function(data) {
                if (data.errorCode === 0) {
                    treeGpsOffline.tree("remove", node.target);
                    refresh_gps();
                }
            });
            break;
    }
};
load_group = function() {
    $.getJSON('php_script/load_group.php', function(data) {
        refresh_gps();
    });
};
//collapse_panel = function(id) {
//    //console.log(id);
//    var pnl = $("#" + id).panel();
//    if (panels[id] !== null)
//    {
//        if (panels[id] === true) {
//            pnl.panel("collapse");
//        } else {
//            pnl.panel("expand");
//        }
//    }
//
//};
clear_tree = function() {
    treeGps.tree({
        data: []
    });
    treeGpsOnline.tree({
        data: []
    });
    treeGpsOffline.tree({
        data: []
    });
};
load_gps_user = function(user_id) {
    //console.log('clear vh_id');
    //$.messager.progress();
    cboGpsId.combobox({
        url: 'php_script/json_combo_vehicle_user.php',
        onBeforeLoad: function(param) {
            // console.log('Load GPS User:'+ user_id);
            param.user_id = user_id;
        },
        valueField: 'id',
        textField: 'nopol',
        onSelect: function(row) {
            vh_id = row.id;
            var root = treeGps.tree('getRoot');
            //  console.log(root);
            var nodes = treeGps.tree('getChildren', root.target);
            for (var j = 0; j < nodes.length; j++) {
                if (nodes[j].text === row.nopol) {
                    treeGps.tree('select', nodes[j].target);
                    select_gps(row.id);
                    var p = treeGps.parent(); // the parent container
                    p.scrollTop(20 * j);
                    break;
                }
            }

        },
        onLoadSuccess: function() {
            $.messager.progress('close');
            //user_id = cboUserId.combobox('getValue');
            console.log('load_gps_user onLoadSuccess');
        }
    });
};

/*
 * Region Trip Report
 */
formatAcc = function(val, row) {
    console.log(val);
    if (parseInt(val, 10) === 1) {
        return "ON";
    }
    if (parseInt(val, 10) === 0) {
        return "OFF";
    }
    return "N/A";
}
;
formatAlarm = function(val, row) {
    var str = "N/A";
    var alarm = parseInt(val, 10);
    switch (alarm) {
        case 1:
            str = "SOS ALARM";
            break;
        case 2:
            str = "POWER CUT ALARM";
            break;
        case 3:
            str = "LOW POWER";
            break;
        case 4:
            str = "SHOCK ALARM";
            break;
        case 5:
            str = "OVER SPEED ALARM";
            break;
        case 6:
            str = "LOW SPEED ALARM";
            break;
        case 7:
            str = "GEOFENCE IN";
            break;
        case 8:
            str = "GEOFENCE OUT";
            break;
        case 9:
            str = "OVERTIME PARK";
            break;
        case 10:
            str = "LOW SPEED ALARM";
            break;
        case 11:
            str = "LOW SPEED ALARM";
            break;
        case 12:
            str = "LOW SPEED ALARM";
            break;
    }
    return str;
}
;


getDataTrip = function() {
    var rows = [];
    for (var i = 0; i < trips.length; i++) {
        rows.push({
            tdate: trips[i].tdate,
            speed: trips[i].speed,
            angle: trips[i].angle,
            acc_state: trips[i].acc_state,
            lat: trips[i].lat,
            lng: trips[i].lng,
            park_until: trips[i].park_until,
            poi: trips[i].poi,
            address: trips[i].address
        });
    }
    return rows;
};

pagerFilter = function(data)
{
    if (typeof data.length === 'number' && typeof data.splice === 'function') {    // is array
        data = {
            total: data.length,
            rows: data
        };
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function(pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
};

init_trip = function() {
    //Init Polyline
    tripPolyline = new google.maps.Polyline({
        strokeColor: "#80ff00",
        strokeOpacity: 0.8,
        strokeWeight: 3
    });
    tripPolyline.setMap(map);

    tripIndex = 0;
    pageNumber = 1;
    tripSpeed = 500;
    goto('tripreport');
};
play = function() {
    if (tripHandler !== '')
        clearTimeout(tripHandler);
    var track = trips[tripIndex];
    var currLatLng = new google.maps.LatLng(track.lat, track.lng);
    var icon = create_icon('images/gps/' + trip_icon, track.speed, track.angle);

    tripMarker.setPosition(currLatLng);
    tripMarker.setIcon(icon);

    var content = "<div>Event:" + get_alarm_name(track.alarm_id) + "</br>";
    content += "Date:" + track.tdate + "</br>";
    content += "Speed:" + track.speed + " Km/jam</br>";
    content += "Lat:" + track.lat + "</br>";
    content += "Lng:" + track.lng + "</br>";

    var strStatistic = "<table>";
    strStatistic += "<tr><td>Kecepatan Rata-rata</td><td>:</td><td>" + avgTripSpeed.toFixed(2) + "Km/Jam</td></tr>";
    strStatistic += "<tr><td>Jarak Tempuh</td><td>:</td><td>" + tripDistance.toFixed(2) + "Km/Jam</td></tr>";
    strStatistic += "<tr><td>Tanggal</td><td>:</td><td class='f12bold'>" + track.tdate + "</td></tr>";
    strStatistic += "</table>";
    panelTripStatistic.html(strStatistic);

    if (infoWindowTrip !== null) {
        infoWindowTrip.setContent(content);
        infoWindowTrip.setPosition(currLatLng);
    }
    if (center_gps_active === true) {
        map.setCenter(currLatLng);
    }

    if (((tripIndex + 1) % 20) === 0) {
        pageNumber++;
        gridTripReport.datagrid("getPager").pagination('select', pageNumber);
        gridTripReport.datagrid({
            onLoadSuccess: function() {
                gridTripReport.datagrid('scrollTo', tripIndex + 1).datagrid('highlightRow', tripIndex + 1);
            }
        });
    } else {
        gridTripReport.datagrid('scrollTo', tripIndex + 1).datagrid('highlightRow', tripIndex + 1);
    }


    if (tripIndex <= trips.length) {
        tripHandler = setTimeout("play();", tripSpeed);
        tripIndex++;
    } else {
        change_trip_state('stop');
    }
};
download_trip_report_excel = function() {

    var vh_id = $("#trip_vh_id").combogrid('getValue');
    var from = to_mysql_date($("#trip_from_date").datebox('getValue')) + " " + $("#trip_from_time").val();
    var to = to_mysql_date($("#trip_to_date").datebox('getValue')) + " " + $("#trip_to_time").val();

    console.log('vh_id:' + id + ',From:' + from + ',To:' + to);
    window.location = "php_script/trip_report_excel.php?vh_id=" + vh_id + "&from=" + from + "&to=" + to;
    return;
};

download_trip_report = function()
{
    change_map_mode("playback");
    //console.log("TO Time:" + $("#trip_to_time").val());
    var vh_id = $("#trip_vh_id").combogrid('getValue');
    var from = to_mysql_date($("#trip_from_date").datebox('getValue')) + " " + $("#trip_from_time").val();
    var to = to_mysql_date($("#trip_to_date").datebox('getValue')) + " " + $("#trip_to_time").val();
    console.log(vh_id + ":" + from + ":" + to);
    $.messager.progress();
    clear_trip();
    init_trip();
    var speedTotal = 0;
    tripReqHandler = $.getJSON('php_script/json_trip_report.php?', {vh_id: vh_id, from: from, to: to},
    function(objects) {
        var no = 0;
        var first = true;
        $.each(objects, function(i, data)
        {
            var speed = parseInt(data.speed);
            if (isNaN(speed) === false) {
                speedTotal += speed;
            }

            var currTrack = {
                tdate: data.tdate,
                tdate2: data.tdate,
                lat: parseFloat(data.lat),
                lng: parseFloat(data.lng),
                alarm_id: data.alarm_id,
                acc_state: parseInt(data.acc_state, 10),
                park: '',
                speed: data.speed,
                angle: parseFloat(data.angle),
                poi: data.poi,
                address: data.address
            };

            if (first === false)
            {
                var prevTrip = trips[no];
                var dist = distance(prevTrip.lat, prevTrip.lng, currTrack.lat, currTrack.lng);
                if (dist <= 5)
                {
                    switch (trips[no].acc_state) {
                        case 0:
                            switch (currTrack.acc_state) {
                                case 1:
                                    prevTrip.tdate2 = data.tdate;
                                    no++;
                                    trips[no] = currTrack;
                                    break;
                                case 0:
                                    prevTrip.tdate2 = data.tdate;
                                    break;
                            }
                            break;
                        case 1:
                            no++;
                            trips[no] = currTrack;
                            break;
                    }
                } else {
                    console.log('Distance More Than 2 Km');
                }
            } else {
                trips[no] = currTrack;
                first = false;
            }
            //Create Marker Event
            if (parseInt(data.alarm_id, 10) > 0)
            {
                var markerEvent = create_marker_event(data);
                if (markerEvent !== null) {
                    tripEventMarker.push(markerEvent);
                }
            }
            //}
        });

        for (var i = 0; i < trips.length; i++) {
            var latlng = new google.maps.LatLng(parseFloat(trips[i].lat), parseFloat(trips[i].lng));
            var path = tripPolyline.getPath();
            path.push(latlng);
        }

        avgTripSpeed = speedTotal / trips.length;
        // var avgSpeed2=avgSpeed.toFixed(2); 
        tripDistance = google.maps.geometry.spherical.computeLength(tripPolyline.getPath().getArray()) / 1000;
        //var distance2=distance.toFixed(2);
        var strStatistic = "<table>";
        strStatistic += "<tr><td>Kecepatan Rata-rata</td><td>:</td><td>" + avgTripSpeed.toFixed(2) + "Km/Jam</td></tr>";
        strStatistic += "<tr><td>Jarak Tempuh</td><td>:</td><td>" + tripDistance.toFixed(2) + "Km/Jam</td></tr>";
        strStatistic += "<tr><td>Tanggal</td><td>:</td><td>" + tripDistance.toFixed(2) + "Km/Jam</td></tr>";
        strStatistic += "<tr><td>Lama Berhenti</td><td>:</td><td>" + tripDistance.toFixed(2) + "Km/Jam</td></tr>";
        strStatistic += "</table>";
        panelTripStatistic.html(strStatistic);

        gridTripReport.datagrid({nowrap: false, fitColumns: false, loadFilter: pagerFilter}).datagrid('loadData', getDataTrip());
        $.messager.progress('close');
        //if available data history, create marker
        console.log("total data history:" + trips.length);
        if (trips.length > 0)
        {
            //Create Marker Playback
            var beginLatlng = new google.maps.LatLng(parseFloat(trips[0].lat), parseFloat(trips[0].lng));
            tripMarker = new google.maps.Marker({
                position: beginLatlng,
                map: map,
                icon: create_icon('images/gps/mobil', trips[0].speed, trips[0].angle)
            });
            google.maps.event.addListener(tripMarker, 'click', function() {
                var str = "<table>";
                str += "<tr><td>Date</td><td>:</td><td>" + trips[tripIndex].tdate + "</td></tr>";
                str += "<tr><td>Speed</td><td>:</td><td>" + trips[tripIndex].speed + "</td></tr>";
                str += "<tr><td>Lat/Lng</td><td>:</td><td>" + trips[tripIndex].lat + "/" + trips[tripIndex].lng + "</td></tr>";
                if (infoWindowTrip === null) {
                    infoWindowTrip = new google.maps.InfoWindow();
                }
                infoWindowTrip.setContent(str);
                infoWindowTrip.open(map, tripMarker);
            });
            map.setCenter(beginLatlng);
            map.setZoom(16);
            //finally calculate distance
            //
            // $("#pb_distance").html(distance.toFixed(2) + " Km");
        }
    });
};

trip_speed = function(speed) {
    switch (speed) {
        case 'slow':
            tripSpeed = 1000;
            break;
        case 'normal':
            tripSpeed = 300;
            break;
        case 'fast':
            tripSpeed = 100;
            break;
        default:
            tripSpeed = 1000;
            break;
    }
};
trip_move = function(move) {
    switch (move) {
        case 'first':
            tripIndex = 0;
            break;
        case 'prev':
            if (tripIndex > 0) {
                tripIndex--;
            }
            break;
        case 'next':
            if (tripIndex < (trips.length - 1)) {
                tripIndex++;
            }
            break;
        case 'last':
            tripIndex = trips.length - 1;
            break;
    }
    gridTripReport.datagrid('scrollTo', tripIndex);
    gridTripReport.datagrid('highlightRow', tripIndex);

    var track = trips[tripIndex];
    var currLatLng = new google.maps.LatLng(track.lat, track.lng);
    var icon = create_icon('images/gps/mobil', track.speed, track.angle);
    if (center_gps_active === true) {
        map.setCenter(currLatLng);
    }
    tripMarker.setIcon(icon);
    tripMarker.setPosition(currLatLng);
    if (infoWindowTrip !== null)
    {
        var content = "<div>Event:" + get_alarm_name(track.alarm_id) + "</br>";
        content += "Date:" + track.tdate + "</br>";
        content += "Speed:" + track.speed + " Km/jam</br>";
        content += "Lat:" + track.lat + "</br>";
        content += "Lng:" + track.lng + "</br>";
        content += "Poi:" + track.poi + "</br>";
        content += "Address:" + track.address + "</div>";
        infoWindowTrip.setContent(content);
        infoWindowTrip.setPosition(currLatLng);
    }
};
trip_move_index = function(index) {
    tripIndex = index;

    var track = trips[tripIndex];
    var currLatLng = new google.maps.LatLng(track.lat, track.lng);
    var icon = create_icon('images/gps/mobil', track.speed, track.angle);
    tripMarker.setIcon(icon);
    tripMarker.setPosition(currLatLng);
    map.setCenter(currLatLng);

    var content = "<div>Event:" + get_alarm_name(track.alarm_id) + "</br>";
    content += "Date:" + track.tdate + "</br>";
    content += "Speed:" + track.speed + " Km/jam</br>";
    content += "Lat:" + track.lat + "</br>";
    content += "Lng:" + track.lng + "</br>";
    content += "Poi:" + track.poi + "</br>";
    content += "Address:" + track.address + "</div>";
    if (infoWindowTrip !== null)
    {
        infoWindowTrip.setContent(content);
        infoWindowTrip.setPosition(currLatLng);
    }
    google.maps.event.trigger(tripMarker, 'click');
};
change_trip_state = function(state) {
    switch (state) {
        case 'play':
            if (pause === false)
                tripIndex = 0;
            google.maps.event.trigger(tripMarker, 'click');
            btnPause.show();
            btnStop.show();
            btnPlay.hide();
            play();
            break;
        case 'pause':
            pause = true;
            btnPause.hide();
            btnStop.hide();
            btnPlay.show();
            clearTimeout(tripHandler);
            break;
        case 'stop':
            clearTimeout(tripHandler);
            btnPause.hide();
            btnStop.hide();
            btnPlay.show();
            pause = false;
            tripIndex = 0;
            pageNumber = 1;
            break;
    }
};

change_page_number = function() {
    var p = $("#pageNumberX").val();
    console.log("Set Page Grid To:" + p);
    pagerGridTripReport = gridTripReport.datagrid("getPager");
    pagerGridTripReport.pagination('select', p);
//    var r1=30%50;
//    var r2=50%50;
//    var r3=90%50;
//    var r4=150%50;
//    
//    console.log("150%50="+ r1);
//    console.log("150%50="+ r2);
//    console.log("150%50="+ r3);
//    console.log("150%50="+ r4);
//     console.log("Set Page Grid To 2:"+ p);
//    gridTripReport.datagrid("load",{
//        pageNumber: p
//    });
};
/*
 * End Trip Report 
 */
$(document).ready(function() {
    // $.messager.progress();
    bound = true;
    layout = ("#cc");
    tabOnline = $("#tabOnline");
    mainTabs = $("#tt");
    mainTabs.tabs("resize");
    btnPlay = $("#btnPlay");
    btnPause = $("#btnPause");
    btnStop = $("#btnStop");
    btnSlow = $("#btnSlow");
    btnNormal = $("#btnNormal");
    btnFast = $("#btnFast");

    treeGps = $("#treeGps").tree();
    treeGpsOnline = $("#treeGpsOnline");
    treeGpsOffline = $("#treeGpsOffline");
    treePoi = $("#treePoi");
    treeGeofence = $("#treeGeofence");

    cboUserId = $('#user_id');
    cboGpsId = $('#vh_id');

    panelInfoGps = $("#panelInfoGps");
    cboPlaybackId = $("#pb_vh_id");
    dlgPoi = $("#dlg_poi");
    formPoi = $("#form_poi");
    dlgProfile = $("#dlg_profile");
    formProfile = $("#form_profile");
    dlgGeofence = $("#dlg_geofence");
    formGeofence = $("#form_geofence");
    jam = $("#jam");


    $('#chk_panel_trip').change(function() {
        if ($(this).is(':checked')) {
            layout2.layout('expand', 'south');
        } else {
            layout2.layout('collapse', 'south');
        }
    });

    cboUserId.combobox({
        url: 'php_script/json_combo_user.php',
        valueField: 'id',
        textField: 'real_name',
        panelWidth: 120,
        onSelect: function(user) {
            user_id = user.id;
            console.log(user);
            bound = true;
            //clear tree
            clear_tree();
            refresh_gps();
            load_gps_user(user_id);
        },
        onLoadSuccess: function() {

            user_id = cboUserId.combobox('getValue');
            console.log('cboUserId-onLoadSuccess:' + user_id);
            refresh_gps();
            load_gps_user(user_id);
        }
    });
    //playback form
    $('#trip_vh_id').combogrid({
        delay: 250,
        panelWidth: 120,
        mode: 'remote',
        url: 'php_script/json_combo_vehicle.php',
        idField: 'id',
        textField: 'nopol',
        columns: [[
                {field: 'id', title: 'Id', width: 20, sortable: true},
                {field: 'nopol', title: 'Nopol', width: 150, sortable: true}
            ]]
    });
    $('#trip_from_date').datebox();
    $('#trip_to_date').datebox();
    displayTime();
    refresh_poi();
    goto('map');

});